const sip = require("sip");
const log4js = require('./logUtils');
const logger = log4js.getLogger('util');
const config = require("../db/config");
const util = require("./stringUtils");
const moment = require("moment");
const settingModel = require("../model/setting");

module.exports={
    /**
     * 去掉没有用的引号
     * @param input
     * @returns {string}
     */
    trim: function (input) {
        return (input || '').replace(/"/g, '');
    },
    generateVia(protocol, params, via0) {
        const via = Object.assign({
            protocol,
            host: settingModel.cache.sip_command_host,
            port: settingModel.cache.sip_command_port,
            version: config.sip.version
        }, via0);

        if (params) {
            via.params = Object.assign({}, params);
        } else {
            // via.params = {branch: sip.generateBranch(),rport: null};
            via.params = {branch: sip.generateBranch()};
        }
        return [via];
    },
    /**
     * 生成uri地址
     * @param {*} deviceId 设备信息
     * @param {*} channelId 通道号，为空表示和 deviceId 一致
     * @param {*} protocol 协议，默认UDP
     * @param {*} host 目标主机
     * @param {*} port 目标端口
     */
    generateUri (deviceId, channelId, protocol, host, port) {
        if (deviceId) {
            let uri;
            if (channelId) {
                uri = `sip:${channelId}@${host}:${port}`;
            } else {
                uri = `sip:${deviceId}@${host}:${port}`;
            }

            if (protocol && protocol.toLowerCase() === 'tcp') {
                uri = uri + ';transport=TCP';
            }
            return uri;
        } else {
            logger.error('deviceid 为空');
            return null;
        }
    },
    /**
     * 生成contact字段值
     */
    buildContact() {
        return [{
            uri:
                'sip:' + settingModel.cache.sip_command_account + '@' + settingModel.cache.sip_command_host + ':' + settingModel.cache.sip_command_port
        }];
    },
    fixHost(input) {
        return input.replace('[::ffff:', '').replace(']', '');
    },
    rstring:function() { return Math.floor(Math.random()*1e6).toString(); },
    // 组合 channel id
    generateChannelId:function(input){
        return config.SIP_CLIENT_PREFIX  + util.padding0(input, 5)
    },
    generateSN:function(){
        return Math.round((new Date()).getTime() / 1000);
    },
    /**
     * 解析 stream_id，有 41010500002000000005_41010500002000000001
     * 或 rtp/proxy/41010500002000000005_41010500002000000001/2024-01-27/20240127-033436_20240127-035436_1201_203849926.mp4
     */
    parseStreamId:function(streamId){
        let deviceId, channelId, deviceChannel, simpleStream;
        let startTime, endTime, date;
        if(streamId.indexOf('/')>-1){
            const timeArray = streamId.split('/');
            deviceChannel = timeArray[1];
            date = timeArray[2];
            const time = timeArray[3];
            const timeArray2 = time.split('_');
            startTime =moment(timeArray2[0], 'YYYYMMDD-HHmmss').unix();
            endTime = moment(timeArray2[1], 'YYYYMMDD-HHmmss').unix();
        }else{
            deviceChannel = streamId;
            startTime = 0;
            endTime = 0;
        }
        const array = deviceChannel.split('_');
        deviceId = array[0];
        channelId = array[1];
        simpleStream = deviceId + '_' + channelId;
        return {deviceId, channelId, simpleStream, date, startTime, endTime};
    }
}
